import { app } from 'electron'
import knex, { Knex } from 'knex'
import { join } from 'path'
import { injectable } from 'inversify'
import 'reflect-metadata'
import { loggerFactory } from '../Log4jFactory'

const dbFilePath = join(app.getPath('userData'), 'local.db')

const logger = loggerFactory('knex')
logger.info(`sqlite3数据库文件路径: ${dbFilePath}`)

// @injectable表明将当前类注入到ioc容器中
@injectable()
export class LocalDB {
  declare db: Knex
  async destroyConnectionPool() {
    await this.db.destroy()
  }
  async init() {
    this.db = knex({
      client: 'sqlite',
      useNullAsDefault: true,
      connection: {
        filename: dbFilePath
      },
      /**
       * 数据库连接池配置
       */
      pool: { min: 2, max: 5 },
      log: {
        warn(message) {
          logger.warn(message)
        },
        error(message) {
          logger.error(message)
        },
        deprecate(message) {
          logger.warn('Knex deprecate日志:', message)
        },
        debug(message) {
          logger.debug(message)
        }
      }
    })
    this.db.on('start', builder => {
      logger.debug(builder.toQuery())
    })
    // 新建表
    await this.sync()
  }

  async sync() {
    // notebooks
    await this.db.schema.hasTable('notebooks').then(exist => {
      if (exist) return
      return this.db.schema.createTable('notebooks', table => {
        table.bigIncrements('id', { primaryKey: true })
        table.string('name')
        table.timestamps(true, true)
      })
    })
    // notes
    await this.db.schema.hasTable('notes').then(exist => {
      if (exist) return
      return this.db.schema.createTable('notes', table => {
        table.bigIncrements('id', { primaryKey: true })
        table.string('name')
        table.text('content')
        table.bigInteger('notebook_id')
        table.timestamps(true, true)
      })
    })
    // media
    await this.db.schema.hasTable('media').then(exist => {
      if (exist) return
      return this.db.schema.createTable('media', table => {
        table.bigIncrements('id', { primaryKey: true })
        table.string('name')
        table.string('local_path') // 本地实际路径
        table.string('sandbox_path') // 沙盒中的地址
        table.bigInteger('note_id')
        table.timestamps(true, true)
      })
    })
  }
}
